#include "mprpcchannel.h"
#include "mprpcapplication.h"
#include "rpcheader.pb.h"
#include "zookeeperutil.h"
#include <arpa/inet.h>
#include <errno.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/service.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
/*
header_size service_name method_name args_size args
*/
void MprpcChannel::CallMethod(const google::protobuf::MethodDescriptor *method,
                              google::protobuf::RpcController *controller, const google::protobuf::Message *request,
                              google::protobuf::Message *response, google::protobuf::Closure *done)
{
    const google::protobuf::ServiceDescriptor *sd = method->service();
    std::string service_name = sd->name();
    std::string method_name = method->name();
    // args
    std::string args_str;
    uint32_t args_size = 0;
    if (request->SerializeToString(&args_str))
    {
        args_size = args_str.size();
    }
    else
    {
        controller->SetFailed("serialize request error");
        return;
    }
    // header
    mprpc::RpcHeader rpcHeader;
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_args_size(args_size);

    std::string rpc_header_str;
    uint32_t header_size = 0;
    if (rpcHeader.SerializeToString(&rpc_header_str))
    {
        header_size = rpc_header_str.size();
    }
    else
    {
        controller->SetFailed("sserialize header error");
        return;
    }
    // 组织rpc请求字符串
    std::string send_rpc_str;
    send_rpc_str.insert(0, std::string((char *)&header_size, 4));
    send_rpc_str += rpc_header_str;
    send_rpc_str += args_str;

    std::cout << "================" << std::endl;
    std::cout << "header_size " << header_size << std::endl;
    std::cout << "rpc_header_str " << rpc_header_str << std::endl;
    std::cout << "service_name " << service_name << std::endl;
    std::cout << "method_name " << method_name << std::endl;
    std::cout << "args_str " << args_str << std::endl;
    std::cout << "================" << std::endl;

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == clientfd)
    {
        controller->SetFailed("create socket error");
        return;
    }
    // std::string ip = MprpcApplication::GetConfig().Load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::GetConfig().Load("rpcserverport").c_str());
    ZkClient zkCli;
    zkCli.Start();
    std::string method_path = "/" + service_name + "/" + method_name;
    std::string host_data = zkCli.GetData(method_path.c_str());
    if (host_data == "")
    {
        controller->SetFailed(method_path + " is not exist");
        return;
    }
    int idx = host_data.find(":");
    if (idx == -1)
    {
        controller->SetFailed(method_path + " is invalid");
        return;
    }
    std::string ip = host_data.substr(0, idx);
    uint16_t port = atoi(host_data.substr(idx + 1, host_data.size() - idx - 1).c_str());

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());

    if (-1 == connect(clientfd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    {
        close(clientfd);
        controller->SetFailed("connect error");
        exit(EXIT_FAILURE);
    }
    if (-1 == send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0))
    {

        close(clientfd);
        controller->SetFailed("send error");
        return;
    }
    // 接收rpc响应
    int recv_size = 0;
    char recv_buf[1024] = {0};
    if (-1 == (recv_size = recv(clientfd, recv_buf, 1024, 0)))
    {
        controller->SetFailed("recv error");
        close(clientfd);
        return;
    }

    if (!response->ParseFromArray(recv_buf, recv_size))
    {
        controller->SetFailed("parse error");
        close(clientfd);
        return;
    }
    close(clientfd);
}
